/* eslint-disable array-callback-return */
import React from 'react';
import { DeleteOutlined, PlusOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import {
  Card,
  Button,
  Spin,
  Select,
  message,
  Steps,
  Divider,
  Row,
  Col,
  InputNumber,
  Table,
  DatePicker,
  Cascader,
} from 'antd';
import { connect } from 'dva';
import router from 'umi/router';
import moment from 'moment';
import queryString from 'query-string';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { isRepeat } from '@/utils/utils';
import HOCSelect from '@/components/AntDesign/Select';

const FormItem = Form.Item;
const { Option } = Select;
const { Step } = Steps;
const { MonthPicker } = DatePicker;

@connect(({ addass, loading, publicdata }) => ({
  loading: loading.models.addass,
  addass,
  dictCode: publicdata.dictCode,
}))
@Form.create()
class BasicForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      addTaskId: null,
    };
  }

  componentDidMount() {
    const { dispatch, location } = this.props;
    const query = queryString.parse(location.search);
    // 获取详情信息
    dispatch({
      type: 'addass/fetchAssDetail',
      payload: query,
    }).then(response => {
      if (query.addTaskId) {
        if (response.success) {
          if (response.data.assList && response.data.assList.length) {
            response.data.assList.map((item, index) => {
              let insKinds = [];
              insKinds = item.assList;
              this.getAcountList(
                response.data.basicInsInfo && response.data.basicInsInfo.areaId,
                `${item.payWay}`,
                insKinds,
                `${item.startYm}-${index}`
              );
              if (item.injSecAccoId) {
                this.getSecAccoList(
                  response.data.basicInsInfo && response.data.basicInsInfo.areaId,
                  `${item.payWay}`,
                  ['5'],
                  `${item.startYm}-${index}`
                );
              }
            });
          }
        } else {
          message.warning(response.message || '获取人员信息：服务端错误');
          router.goBack();
        }
      }
    });
    this.setState({ addTaskId: query.addTaskId || null });
  }

  componentWillUnmount() {
    const { dispatch } = this.props;
    const dataInfo = {
      // 增加险种前查看
      assList: [], // 已有社保信息
      basicInsInfo: {}, // 基本信息
      tableId: 1,
      assVoList: [
        {
          id: 0,
          assList: [],
          payWay: undefined, // 缴费方式
          payWayList: [],
          accoId: undefined, // 缴费账户
          accountList: [], // 缴费账户列表
          injSecAccoId: undefined, // 工伤二级户
          isHasInj: false, // 有无工伤险
          secAccuList: [], // 工伤二级户列表
          startYm: undefined,
          isSupplyRun: false, // 是否是供应商执行
          kinds: undefined, //  选中的险种
        },
      ],
    };
    dispatch({
      type: 'addass/updateModelData',
      payload: { ...dataInfo },
    });
  }

  // 添加列表
  addList = () => {
    const {
      dispatch,
      addass: { tableId, assVoList, basicInsInfo },
    } = this.props;
    const newData = {
      id: tableId,
      assList: basicInsInfo.assList,
      payWay: undefined, // 缴费方式
      payWayList: basicInsInfo.payWayList,
      accoId: undefined, // 缴费账户
      accountList: [], // 缴费账户列表
      injSecAccoId: undefined, // 工伤二级户
      isHasInj: false, // 有无工伤险
      secAccuList: [], // 工伤二级户列表
      startYm: undefined,
      kinds: undefined,
      isSupplyRun: basicInsInfo.execType === 2 || false,
    };
    dispatch({
      type: 'addass/updateModelData',
      payload: {
        assVoList: [...assVoList, newData],
        tableId: tableId + 1,
      },
    });
  };

  // 删除列表
  deleteList = id => {
    const {
      dispatch,
      addass: { assVoList },
    } = this.props;
    dispatch({
      type: 'addass/updateModelData',
      payload: { assVoList: assVoList.filter(item => item.id !== id) },
    });
  };

  // 选择险种
  selectKinds = (value, id) => {
    const isHasInj = value.indexOf(5) > -1; //  是否有工伤险
    const {
      dispatch,
      addass: { assVoList, areaId },
      form,
    } = this.props;
    // 更新当前表格数据;
    dispatch({
      type: 'addass/updateTableData',
      payload: { targetKey: 'kinds', value, id },
    });
    dispatch({
      type: 'addass/updateTableData',
      payload: { targetKey: 'accoId', value: undefined, id },
    });
    dispatch({
      type: 'addass/updateTableData',
      payload: { targetKey: 'injSecAccoId', value: undefined, id },
    });
    dispatch({
      type: 'addass/updateTableData',
      payload: { targetKey: 'isHasInj', value: isHasInj, id },
    });
    form.resetFields([`assVoList[${id}][accoId]`]);
    // 判断是否是工伤二级户;
    let isSecAccu = false;
    const insKinds = value;
    let payWay = null;
    let isSupplyRun = false;
    assVoList.forEach(item => {
      if (item.id === id) {
        isSecAccu = areaId === '1415662' && item.payWay === '2' && isHasInj;
        // eslint-disable-next-line prefer-destructuring
        payWay = item.payWay;
        // eslint-disable-next-line prefer-destructuring
        isSupplyRun = item.isSupplyRun;
      }
    });
    if (payWay && value.length) {
      // 存在缴费方式
      if (payWay === '1' || (payWay === '2' && !isSupplyRun)) {
        this.getAcountList(areaId, payWay, insKinds, id);
      }
      // 工伤二级户
      if (isSecAccu && insKinds.length && payWay === '2' && !isSupplyRun) {
        // 获取工伤二级户
        this.getSecAccoList(areaId, payWay, ['5'], id);
      }
    }
  };

  // 选择缴费方式
  selectPayWay = (value, id) => {
    const {
      dispatch,
      addass: { assVoList, areaId },
      form,
    } = this.props;
    // 更新当前表格数据
    dispatch({
      type: 'addass/updateTableData',
      payload: { targetKey: 'payWay', value, id },
    });
    dispatch({
      type: 'addass/updateTableData',
      payload: { targetKey: 'accoId', value: undefined, id },
    });
    dispatch({
      // 缴费账户列表重置
      type: 'addass/updateTableData',
      payload: { targetKey: 'accountList', value: [], id },
    });
    // 工伤二级户
    dispatch({
      type: 'addass/updateTableData',
      payload: { targetKey: 'injSecAccoId', value: undefined, id },
    });
    dispatch({
      type: 'addass/updateTableData',
      payload: { targetKey: 'secAccuList', value: [], id },
    });
    form.resetFields([`assVoList[${id}][accoId]`]);
    let isSecAccu = false; // 工伤二级户
    let insKinds = [];
    let isSupplyRun = false;
    assVoList.forEach(item => {
      if (item.id === id) {
        isSecAccu = areaId === '1415662' && value === '2' && item.isHasInj;
        insKinds = item.kinds || [];
        // eslint-disable-next-line prefer-destructuring
        isSupplyRun = item.isSupplyRun;
      }
    });
    // console.log('insKinds', assVoList, insKinds);
    if (insKinds.length && (value === '1' || (value === '2' && !isSupplyRun))) {
      this.getAcountList(areaId, value, insKinds, id);
    }
    if (isSecAccu && !isSupplyRun) {
      this.getSecAccoList(areaId, value, ['5'], id);
    }
  };

  // 选择缴费账户
  selectAccount = (value, options, id) => {
    const { dispatch } = this.props;
    // 更新当前表格数据
    dispatch({
      type: 'addass/updateTableData',
      payload: { targetKey: 'accoId', value, id },
    });
  };

  // 选择工伤二级户
  selectSecAcco = (value, options, id) => {
    const { dispatch } = this.props;
    if (value.length === 1) {
      return message.warning(`请选择"${options[0].accoName}"的二级户`);
    }
    // 更新当前表格数据
    dispatch({
      type: 'addass/updateTableData',
      payload: { targetKey: 'injSecAccoId', value: value[value.length - 1], id },
    });
    return null;
  };

  // 获取缴费账户列表
  getAcountList = (areaId, payWay, insKinds, id) => {
    const {
      dispatch,
      addass: {
        basicInsInfo: { custId },
      },
    } = this.props;
    dispatch({
      type: 'addass/fetchAcountList',
      payload: {
        custId,
        areaId,
        insKinds,
        payWay,
        id,
      },
    });
  };

  // 获取工伤二级户列表
  getSecAccoList = (areaId, payWay, insKinds, id) => {
    const {
      dispatch,
      addass: {
        basicInsInfo: { custId },
      },
    } = this.props;
    if (custId && areaId && payWay && insKinds.length) {
      dispatch({
        type: 'addass/fetchSecAccoList',
        payload: {
          custId,
          areaId,
          insKinds,
          payWay,
          id,
        },
      });
    }
  };

  // 提价数据
  submit = () => {
    const { dispatch, form } = this.props;
    const { addTaskId } = this.state;
    form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        if (values.assVoList) {
          const assVoList = [];
          const assList = [];
          const obj = values;
          // eslint-disable-next-line no-unused-vars
          Object.entries(values.assVoList).forEach(([_, value]) => {
            if (value) {
              const temp = value;
              temp.startYm = value.startYm && value.startYm.format('YYYY-MM-01');
              temp.injSecAccoId =
                value.injSecAccoId && value.injSecAccoId[value.injSecAccoId.length - 1];
              assVoList.push(value);
              if (value.assList && value.assList.length) {
                value.assList.forEach(ass => {
                  assList.push({ ass });
                });
              }
            }
          });
          if (isRepeat(assList, 'ass')) {
            message.warning('所选险种名称重复，请重新选择！');
            return;
          }
          obj.assVoList = assVoList;
          dispatch({
            type: 'addass/submit',
            payload: { addTaskId, values },
          });
        } else {
          message.warning('请添加增加险种配置！');
        }
      }
    });
  };

  render() {
    const {
      loading,
      form: { getFieldDecorator },
      addass: { assList, basicInsInfo, assVoList },
    } = this.props;
    const { addTaskId } = this.state;

    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 9 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 10 },
      },
    };
    const assColumns = [
      {
        title: '险种',
        dataIndex: 'assName',
        align: 'center',
      },
      {
        title: '执行地',
        dataIndex: 'cityName',
        align: 'center',
      },
      {
        title: '执行方',
        dataIndex: 'execTypeName',
        align: 'center',
      },
      {
        title: '申报工资',
        dataIndex: 'decWage',
        align: 'center',
      },
      {
        title: '业务开始日期',
        dataIndex: 'startYm',
        align: 'center',
        render: val => (val && moment(val).format('YYYY-MM-DD')) || '--',
      },
      {
        title: '业务结束日期',
        dataIndex: 'endYm',
        align: 'center',
        render: val => (val && moment(val).format('YYYY-MM-DD')) || '--',
      },
      {
        title: '缴费方式',
        dataIndex: 'payWayName',
        align: 'center',
      },
      {
        title: '缴费账户',
        dataIndex: 'accoName',
        align: 'center',
      },
      {
        title: '社保组合',
        dataIndex: 'grpName',
        align: 'center',
      },
    ];

    return (
      <Form>
        <PageHeaderWrapper>
          <Spin tip="Loading..." spinning={loading}>
            <Card>
              {!addTaskId && (
                <Steps current={1} style={{ marginBottom: 70 }}>
                  <Step title="选择人员" />
                  <Step title="填写险种信息" />
                  <Step title="完成" />
                </Steps>
              )}
              {!addTaskId && (
                <Card
                  title={<span style={{ fontWeight: 'bolder' }}>社保信息</span>}
                  style={{ border: 'none' }}
                >
                  <Table
                    columns={assColumns}
                    dataSource={assList}
                    rowKey={(_, index) => index}
                    bordered
                    size="middle"
                    pagination={false}
                  />
                </Card>
              )}
              <Card
                title={
                  <span style={{ fontWeight: 'bolder' }}>
                    {addTaskId ? '修改' : '添加'}社保险种
                  </span>
                }
                style={{ border: 'none' }}
              >
                {assVoList.map((item, index) => (
                  <Row gutter={24} key={item.id}>
                    {index > 0 && (
                      <Col span={22}>
                        <Divider dashed />
                      </Col>
                    )}
                    <Col span={22} style={{ position: 'relative' }}>
                      <FormItem
                        label={
                          <span>
                            选择险种
                            <span style={{ fontSize: '12px', color: '#999' }}>(可多选)</span>
                          </span>
                        }
                        {...formItemLayout}
                      >
                        {getFieldDecorator(`assVoList[${item.id}][assList]`, {
                          rules: [{ required: true, message: '请选择' }],
                          initialValue: item.kinds,
                        })(
                          <HOCSelect
                            placeholder="请选择"
                            mode="multiple"
                            style={{ width: '100%' }}
                            showSearch
                            optionFilterProp="children"
                            onChange={value => this.selectKinds(value, item.id)}
                          >
                            {item.assList.map(options => (
                              <Option key={options.ass} value={options.ass}>
                                {options.assName}
                              </Option>
                            ))}
                          </HOCSelect>
                        )}
                      </FormItem>
                      {index > 0 && (
                        <DeleteOutlined
                          onClick={() => this.deleteList(item.id)}
                          style={{
                            cursor: 'pointer',
                            position: 'absolute',
                            right: '180px',
                            top: 10,
                            fontSize: '16px',
                            color: '#1890FF',
                          }}
                        />
                      )}
                    </Col>
                    <Col span={22}>
                      <FormItem label="社保组合" {...formItemLayout}>
                        <span>{basicInsInfo.grpName || '--'}</span>
                      </FormItem>
                    </Col>
                    <Col span={22}>
                      <FormItem label="申报工资" {...formItemLayout}>
                        {getFieldDecorator(`assVoList[${item.id}][decWage]`, {
                          rules: [
                            {
                           required: true,
                           message: '请输入整数',
                           pattern: /^[1-9]\d*$/, 
                          }],
                          initialValue: item.decWage,
                        })(
                          // <InputNumber
                          //   min={0}
                          //   max={9999999.99}
                          //   precision={2}
                          //   placeholder="请输入"
                          //   style={{ width: '100%' }}
                          // />
                          <InputNumber
                            min={0}
                            max={9999999.99}
                            precision={2}
                            placeholder="请输入"
                            style={{ width: '100%' }}
                          />
                        )}
                      </FormItem>
                    </Col>
                    <Col span={22}>
                      <FormItem label="缴费方式" {...formItemLayout}>
                        {getFieldDecorator(`assVoList[${item.id}][payWay]`, {
                          rules: [{ required: true, message: '请选择' }],
                          initialValue: item.payWay,
                        })(
                          <HOCSelect
                            placeholder="请选择"
                            showSearch
                            optionFilterProp="children"
                            style={{ width: '100%' }}
                            onSelect={value => this.selectPayWay(value, item.id)}
                          >
                            {item.payWayList.map(options => (
                              <Option key={options.payWay}>{options.payWayName}</Option>
                            ))}
                          </HOCSelect>
                        )}
                      </FormItem>
                    </Col>
                    {!(item.isSupplyRun && item.payWay === '2') && (
                      <Col span={22}>
                        <FormItem label="缴纳账户" {...formItemLayout}>
                          {getFieldDecorator(`assVoList[${item.id}][accoId]`, {
                            rules: [{ required: item.payWay === '1', message: '请选择' }],
                            initialValue: item.accoId,
                          })(
                            <HOCSelect
                              placeholder="请选择"
                              allowClear={item.payWay === '2'}
                              showSearch
                              optionFilterProp="children"
                              style={{ width: '100%' }}
                              onSelect={(value, options) =>
                                this.selectAccount(value, options, item.id)
                              }
                            >
                              {item.accountList.map(options => (
                                <Option
                                  key={options.accoId}
                                  value={options.accoId}
                                  fsOptions={options}
                                >
                                  {options.accoName}
                                </Option>
                              ))}
                            </HOCSelect>
                          )}
                        </FormItem>
                      </Col>
                    )}
                    {basicInsInfo.areaId === '1415662' &&
                      item.payWay === '2' &&
                      !item.isSupplyRun &&
                      item.isHasInj && (
                        <Col span={22}>
                          <FormItem label="工伤二级户" {...formItemLayout}>
                            {getFieldDecorator(`assVoList[${item.id}][injSecAccoId]`, {
                              rules: [{ required: true, message: '请选择' }],
                              initialValue: item.injSecAccoId,
                            })(
                              <Cascader
                                placeholder="请输入关键字检索"
                                options={item.secAccuList}
                                showSearch
                                notFoundContent="暂无工伤二级户"
                                style={{ width: '100%' }}
                                onChange={(value, options) =>
                                  this.selectSecAcco(value, options, item.id)
                                }
                                changeOnSelect
                              />
                            )}
                          </FormItem>
                        </Col>
                      )}
                    <Col span={22}>
                      <FormItem label="业务开始日期" style={{ width: '100%' }} {...formItemLayout}>
                        {getFieldDecorator(`assVoList[${item.id}][startYm]`, {
                          rules: [{ required: true, message: '请选择' }],
                          initialValue: (item.startYm && moment(item.startYm)) || undefined,
                        })(
                          <MonthPicker
                            placeholder="请选择"
                            format="YYYY-MM-01"
                            allowClear={false}
                            style={{ width: '100%' }}
                          />
                        )}
                      </FormItem>
                    </Col>
                  </Row>
                ))}
                <Row gutter={24}>
                  <Col span={8} />
                  <Col span={10}>
                    <Button type="dashed" onClick={this.addList} style={{ width: '95%' }}>
                      <PlusOutlined /> 添加
                    </Button>
                  </Col>
                  <Col span={6} />
                </Row>
                <Row gutter={24}>
                  <Col span={8} />
                  <Col span={8} style={{ color: '#999', fontSize: '12px', marginTop: 10 }}>
                    说明：如果险种缴纳信息不同，可点击继续添加，分险种设置
                  </Col>
                  <Col span={8} />
                </Row>
              </Card>
              <div style={{ marginTop: '100px', marginBottom: '30px', textAlign: 'center' }}>
                <Button style={{ marginRight: '30px' }} onClick={() => router.goBack()}>
                  返回
                </Button>
                <Button type="primary" onClick={this.submit}>
                  提交
                </Button>
              </div>
            </Card>
          </Spin>
        </PageHeaderWrapper>
      </Form>
    );
  }
}

const BasicFormList = Form.create()(BasicForm);
export default BasicFormList;
